/**
 * ECP Web开发弹出树选择窗口控件.
 * Copyright(c) 2012-2020 YGSoft.Inc
 * @author zhengxianwei 
 * @date 2016-04-13
 */
define(["jquery","ecp.service","jstree","ecp.utils","ecp.utils.tree","ecp.component.dialog","ecp.utils.i18n","ecp.locate"],function($,ecp,jstree,utils,treeUtils,$window,i18n, locate){
	/**
	 * 默认参数.
	 */
	var defaultOptions = {
		winOption: {
			title:i18n.select.treeTitle,
			url : "/grm/ecp/webcore/components/select/poptree.html",  //远程url 获取html片段
			fade : false,  //取消动画效果
			multilayer : true,  //允许多次嵌套模态窗
            width : "600px",   //模态窗宽度 支持如 100% 600px
            maxHeight : "506px"  //模态窗body最大高度，超过时body内将出现滚动条
		}
	};

	/**
	 * 保存选中的记录数
	 */
	var selectNodeDatas = {};
	
	/**
	 * 声明TreeSelect对象.
	 * @param {option} option 控件的属性对象
	 */
	var PopTree = function(option){
		//初始化
		this._init(option);
		//渲染控件
		this._render();
	}
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	PopTree.prototype = {
			/**
			 * 初始化.
	    	 * @param {Object} option 控件的属性对象
			 */
			_init: function(option){
				this.option = option;
			},
			
			/**
	    	 * 初始化渲染.
	    	 */
			_render: function(){
				var me = this,
					opt = $.extend(true,{},defaultOptions.winOption,me.option.winOption,{
		                callback:function(container){
		                	//国际化
		                	utils.loadLocale(i18n.select,container);
		    				utils.domAttrI18n(i18n.select, container, "title");
		    				utils.domAttrI18n(i18n.select, container, "placeholder");
		    				//渲染树
		                	me._renderTree();
		                	//显示实体窗回调
		                	if($.isFunction(me.option.showCallBack)){
		                		me.option.showCallBack.call(me,container,me.option);
		                	}
		                },
		                dialogHide:function(){
		                	selectNodeDatas = {};
		                },
		                showCloseButton:false,
		                offClick :true,  //取消点击非模态窗位置关闭窗口
		                otherButtons:[i18n.select.cancel,i18n.select.sure],  //增加两个按钮
		                otherButtonStyles:['btn-default','btn-primary'], //按钮样式,
		                clickButton:function(sender, modal, index){
		                	if(index == 1){  //确定按钮
		                		me._sureBtn();
		                	}
		                	if(index == 0){  //取消按钮
		                		modal.modal("hide");
		                	}
		                }
					});
				me.winContainer = $window.window(opt);
	    	},
	    	
	    	/**
	    	 * 显示窗口.
	    	 */
	    	show: function(){
	    		var me = this;
	    		this.winContainer.modal("show");
	    		this._renderTree();
	    		$("[buttonindex]",this.winContainer).off("click").on("click",function(event){
	    			//确认
	    			if($(event.target).attr("buttonindex") == 1){
	    				me._sureBtn();
	    			}
	    			me.hide();
	    		})
	    	},
	    	/**
	    	 * 隐藏窗口.
	    	 */
	    	hide: function(){
	    		this.winContainer.modal("hide");
	    	},
	    	
	    	/**
	    	 * 渲染树控件.
	    	 */
	    	_renderTree: function(){
	    		var me = this,
	    			opt = me.option,
	    			treeOpt = opt.treeOptions,
	    			plugins = ["types", "search","create_node"],
	    			treeObj = $("#tree_entity", this.winContainer);
	    		if(opt.multiple){
	    			plugins.push("checkbox");
	    		}
	    		var treeOption = {
 						"treeCodeField":treeOpt.treeCodeField,
 						"treeTextField":treeOpt.treeTextField,
 						"treeType":treeOpt.treeType,
 						"treeValueField":treeOpt.treeValueField,
 						"treeFieldName":treeOpt.buildTreeField,
 						"treeCodePolicy":treeOpt.treeCodePolicy
 				};
	    		var initTreeFn = function(resultData){
	    			var treeData = treeUtils.getJsTreeJson(resultData,treeOpt);
	    			var plug = treeOpt && treeOpt.plugins;
	    			me.sourceData = resultData;
	 				treeObj.data("treeOption",treeOption);
	 				treeObj.jstree("destroy");
	 				plugins = $.extend(true, plugins, plug);
	 				me._bindTreeEvent();
	 				var _opt = {
 						"core" : {
	 				      "themes" : {
	 				        "responsive": false,
					        "icons":false
	 				      },
	 				      'data': treeData
	 				    },
	 				    "types" : {
	 				      "default" : {
	 				        "icon" : "fa fa-folder icon-warning icon-lg"
	 				      },
	 				      "file" : {
	 				        "icon" : "fa fa-file icon-warning icon-lg"
	 				      }
	 				    },
	 				    "plugins": plugins	
	 				}
	 				_opt = $.extend(true,{},_opt,treeOpt);
	 				treeObj.jstree(_opt);
	    		}
	    		var data = opt.data;
	    		var treeDatas = this.option.treeDatas;
	    		if($.isFunction(treeDatas)){
	    			treeDatas.call(this, this.option, initTreeFn);
	    		}else if(data && data.length !== 0){
	    			initTreeFn(data);
	    		}
	    	},
	    	
	    	/**
	    	 * 节点可用和不可用设置
	    	 * @param {String | Array} ids id值 
	    	 */
	    	_disableOrEnable: function(ids, ableName){
	    		var data = this.sourceData;
	    		if(!utils.notEmpty(ids) || !utils.notEmpty(data)){
	    			return;
	    		}
	    		var me = this,
	    			treeObj = me.getTreeObject(),
	    			id, treeCodeField = me.option.treeOptions.treeCodeField;
	    		if(typeof(ids) === "string"){
	    			ids = ids.split(",");
	    		}
    			$.each(data,function(i,d){
    				id = d[treeCodeField];
    				if($.inArray(id, ids) >= 0){
						treeObj.jstree(ableName, id);
    				}
    			})
	    	},
	    	
	    	/**
	    	 * 节点不可用.
	    	 * @param {String | Array} ids id值 
	    	 */
	    	disable: function(ids){
	    		var disableCb = this.option.disableCallBack;
	    		if(ids === undefined && $.isFunction(disableCb)){
	    			ids = disableCb.call(this,this.getTreeObject());
	    		}
	    		this._disableOrEnable(ids, "disable_node");
	    	},
	    	
	    	/**
	    	 * 节点可用.
	    	 * @param {String | Array} ids id值 
	    	 */
	    	enable: function(ids){
	    		var enableCb = this.option.enableCallBack;
	    		if(ids === undefined && $.isFunction(enableCb)){
	    			ids = enableCb.call(this,this.getTreeObject());
	    		}
	    		this._disableOrEnable(ids, "enable_node");
	    	},
	    	
	    	/**
	    	 * 获得树对象
	    	 */
	    	getTreeObject: function(){
	    		return $("#tree_entity", this.winContainer);
	    	},
	    	
	    	/**
	    	 * 设置树的选中值
	    	 * @param {Array} data 数据
	    	 */
	    	setSelectValue: function(data){
	    		this.selectDatas = data;
	    	},
	    	/**
	    	 * 设置树的选中值
	    	 * @param {Array} data 数据
	    	 */
	    	_setSelectValue: function(){
	    		var data = this.selectDatas;
	    		if(!data){return;}
	    		var me = this,
	    			opt = this.option,
	    			treeObj = $("#tree_entity", this.winContainer);
	    		//默认选中树节点
	    		if(data && data.length !== 0){
//	    			var idField = opt.idField;
	    			var codeField = opt.treeOptions.treeCodeField;
		    		me.timeoutSetVal = window.setInterval(function(){
						if(me.isLoadData === true){
							if(opt.multiple){
			    				$.each(data,function(i,d){
				    				treeObj.jstree("select_node",d[codeField]);
				    			})
			    			}else{
			    				treeObj.jstree("select_node",data[codeField]);
			    			}
							window.clearInterval(me.timeoutSetVal);
							delete me.isLoadData;
							delete me.timeoutSetVal;
						}
					},50)
	    		}
	    	},
	    	
	    	/**
			 * 树查找无结果时给提示.
			 */
			checkTreeSearch: function(val){
				var me = this,
					container = me.winContainer,
					treeObj = $("#tree_entity", container);
				treeObj.jstree(true).search(val);
				if(treeObj.find("a.jstree-search").length === 0 && utils.notEmpty(val)){
					utils.notify({
						message:i18n.select.noMatchRecords,
				        delay:1000//延迟3秒关闭
					}); 
				}
			},
			/**
			 * 绑定的树事件.
			 */
			_bindTreeEvent: function(){
				var me = this,
	    			opt = me.option,
	    			treeOpt = opt.treeOptions,
					container = me.winContainer,
					treeObj = $("#tree_entity", container);
		    	//展开缩起节点.
		    	$("#btn_entityTreeExpand", container).off("click").on("click", function(){
		 			var treeObj = $("#tree_entity", container);
		 			//修正全部关闭条件，只要不存在jstree-closed样式才全部关闭 modi by zxw
		 			var nodes = treeObj.jstree('get_container_ul').find(".jstree-closed");
		 			if (nodes.length === 0) {
						 treeObj.jstree("close_all");
						 $(this).find("i").removeClass("iconfont icon-quanbushouqi").addClass("fa fa-arrows")						 
		 			} else {
						 treeObj.jstree("open_all");
						 $(this).find("i").removeClass("fa fa-arrows").addClass("iconfont icon-quanbushouqi")
		 			}
		 		});
		 		//搜索
				var isEnterFlag = false;
				// 搜索框keyup事件
// 				$("#entity_search", container).off("keyup").on("keyup", function(e) {
// 					var $me = this;
// 					isEnterFlag = false;
// 					if (e.keyCode == "13") {
// 						isEnterFlag = true;
// 						me.checkTreeSearch($me.value.trim());
// //						treeObj.jstree(true).search($me.value.trim());
// 					}else{
// 						if(this.timeout){
// 							  window.clearTimeout(this.timeout)
// 						}
// 						this.timeout = window.setTimeout(function(){
// 							if(isEnterFlag === false){
// 								me.checkTreeSearch($me.value.trim());
// //								treeObj.jstree(true).search(me.value.trim());
// 							}
// 						},900)
// 					}
// 				});
				locate.render({
					container: $('#entity_search',container), //必须
					jstreeObject: $('#tree_entity',container),//必须
					callback: function(val){ //可选 触发搜索后的回调
					},
					width: '300px',//可选 默认300px
					placeholder: '输入关键字 , 自动定位'//可选 无特殊情况不需配置该选项
				});

//				treeObj.bind("loaded.jstree", function (event, data) {
////		            data.instance.open_all(); // -1 opens all nodes in the container
//		        });
	    		//树的展开事件.
				treeObj.bind("open_node.jstree",function(event,data){
					
					var treeLazyDatas = opt.treeLazyDatas;
					if(opt.isLazy !== true || !$.isFunction(treeLazyDatas)){return;}
					var node = data.node;
					//顶层节点展开不做处理.
					if(node.parent=="#"){
						//分类做为树时特殊处理
						var ids = node.children;
						for(var i=0, len=ids.length; i<len; i++){
							var _node = data.instance.get_node(ids[i]);
							if(!_node.original.leaf){
								_node.children.push(ids[i]);
								_node.children_d.push(ids[i]);
								_node.state.opened=false;
								$("#"+ids[i], container).attr("class","jstree-node  jstree-closed");
							}
						}
						return;
					}
					var callback = function(result){
							if(!result || result.length === 0){return;}
							var res = treeUtils.getJsTreeJson(result, treeOpt);
							treeObj.jstree(true)._append_json_data(node, res , function(){});
					}
					//树节点懒加载回调函数
					var filter = {
							id : node.id,
							parent: node.parent,
							text: node.text,
							original: node.original
					}
					treeLazyDatas.call(this, opt, callback, filter);
					
	    		}).bind("ready.jstree",function(){
					//选择树节点事件
					me.isLoadData = true;
	    		}).bind("select_node.jstree",function(event,data){
					//选择树节点事件
	    			//todo
	    		}).bind("loaded.jstree",function(e,data){
                    data.instance.open_all("#");
                    me._setSelectValue();
                    me.disable();
                    if($.isFunction(me.loadedCallback)){
                    	loadedCallback.call(me, treeObj, opt, container);
                    }
                });
                //单选绑定双击退出
                if(!opt.mutiple){
                    treeObj.bind("dblclick",function(event){
                        if(event.target.tagName === "A"){
                            me._sureBtn();
                        }
                    })
                }
				//绑定用户设置的事件
				if(utils.notEmpty(me.treeEvents)){
					$.each(me.treeEvents,function(){
						treeObj.bind(this.event,this.handler);
					})
				}
			},
			
			/**
			 * 展开节点.
			 */
			expendNode: function(){
				
			},
			
			/**
			 * 确定按钮
			 */
			_sureBtn: function(){
				var me = this,
	    			option = me.option,
	    			control = me.control,
	    			container = me.winContainer,
					treeObj = $("#tree_entity", container);
				//获得选中树节点id
	 			var selectData = treeObj.jstree().get_selected(true);
	 			if(selectData && selectData.length !==0){
	 				var popSelected = [];
	 				for(var i = 0,j=selectData.length; i<j; i++){
						popSelected.push(selectData[i].original);
    				}
	 			}else{
	 				utils.notify(i18n.select.selectOneRecord);
	 				return;
	 			}
	 			container.modal("hide");
				option.closeCallBack && option.closeCallBack(popSelected);
			},
	    	
	    	/**
	    	 * 绑定树事件
	    	 */
	    	bindTreeEvent: function(event,handler){
	    		if(utils.notEmpty(event) && utils.notEmpty(handler)){
	    			if(!this.treeEvents){this.treeEvents = [];}
	    			this.treeEvents.push({event:event,handler:handler});
	    		}
	    	},
	    	
	    	/**
	    	 * 解除树事件
	    	 */
	    	unBindTreeEvent: function(event){
	    		if(utils.notEmpty(event)){
	    			var te = this.treeEvents;
	    			if(te && te.length !== 0){
	    				for(var i=te.length-1; i>=0; i--){
	    					if(te[i].event === event){
	    						te.removeAt(i);
	    					}
	    				}
	    			}
	    		}
	    	},
	    	
	    	/**
	    	 * 设置option.
	    	 * @param {Object} option 控件属性
	    	 */
	    	setOption:function(option){
	    		if(!option || !$.isPlainObject(option) || $.isEmptyObject(option)){
	    			return;
	    		}
	    		this.option = $.extend(true,this.option,option);
	    	},
	    	
	    	/**
	    	 * 获取options
	    	 * @return {Object} option 控件属性对象
	    	 */
	    	getOption:function(){
	    		return this.option;
	    	},
	    	
	    	/**
	    	 * 赋数据.
	    	 * @param {Object} data 实体数据
	    	 */
	    	setData: function(data){
	    		this.data("ecp_treeSelect",data);
	    	},
	    	
	    	/**
	    	 * 获得数据.
	    	 * @return {Object} data 数据对象
	    	 */
	    	getData: function(){
	    		return this.data("ecp_treeSelect");
	    	}
	};
	return PopTree;
});